package com.qunduikj.sjb.sdk;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.widget.ImageView;

import com.litesuits.android.log.Log;
import com.litesuits.http.HttpConfig;
import com.litesuits.http.exception.HttpException;
import com.litesuits.http.listener.GlobalHttpListener;
import com.litesuits.http.listener.HttpListener;
import com.litesuits.http.request.AbstractRequest;
import com.litesuits.http.request.JsonRequest;
import com.litesuits.http.request.param.HttpMethods;
import com.litesuits.http.request.param.HttpRichParamModel;
import com.litesuits.http.response.Response;
import com.litesuits.orm.db.DataBaseConfig;
import com.litesuits.sdk.LiteSdk;
import com.litesuits.sdk.config.LiteConfig;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;
import com.qunduikj.sjb.R;
import com.qunduikj.sjb.sdk.config.ApiConfig;
import com.qunduikj.sjb.sdk.consts.AppConst;
import com.qunduikj.sjb.sdk.handler.UncaughtHandler;
import com.qunduikj.sjb.sdk.model.api.ApiModel;
import com.qunduikj.sjb.sdk.model.api.login.LoginModel;
import com.qunduikj.sjb.sdk.model.api.login.LoginParam;
import com.qunduikj.sjb.sdk.model.enums.ErrorCode;
import com.qunduikj.sjb.sdk.model.user.User;
import com.umeng.analytics.MobclickAgent;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

/**
 * @author MaTianyu on 2015-05-05
 */
public class AppSdk extends LiteSdk {
    protected static final String TAG = AppSdk.class.getSimpleName();
    protected static AppSdk instance;
    protected User user;
    protected static CountDownLatch latch = new CountDownLatch(1);


    public static void initialize(final Context context) {
        if (instance == null) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    instance = new AppSdk(context.getApplicationContext());
                    latch.countDown();
                }
            }).start();
        }
    }

    public synchronized static AppSdk getInstance() {
        try {
            latch.await(4900, TimeUnit.MILLISECONDS);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return instance;
    }

    private AppSdk(Context context) {
        super(context);
        // init user
        user = (User) dataKeeper.get(AppConst.KEY_USER);
        if (user == null) {
            user = new User();
        }
        initImageLoader();
        MobclickAgent.setDebugMode(LiteConfig.debuged);//普通测试  混淆真实数据
        MobclickAgent.openActivityDurationTrack(false);//不自动统计activity
    }

    public String getAppVersionName() {
        String versionName = null;
        try {
            // ---get the package info---
            PackageManager pm = context.getPackageManager();
            PackageInfo pi = pm.getPackageInfo(context.getPackageName(), 0);
            versionName = pi.versionName;
        } catch (Exception e) {
            Log.e("VersionInfo", "Exception", e);
        }
        return versionName == null ? "1.0.0.def" : versionName;
    }

    @Override
    protected HttpConfig createHttpConfig() {
        return new HttpConfig(context)
                .setDebugged(LiteConfig.debuged)//是否开启调试模式，log日志
                .setGlobalSchemeHost(ApiConfig.API_HOST_V1)//服务器地址
                .setDefaultHttpMethod(HttpMethods.Post)//请求方式
                .setDefaultMaxRetryTimes(1)
                        //                .setUserAgent("User-Agent:Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0;")
                .setGlobalHttpListener(new GlobalHttpListener() {
                    @Override
                    public void onSuccess(Object o, Response<?> response) {
                        Log.i(TAG, "global request: " + response.getRequest().getUri() + "  ,response: " + response
                                .getRawString());
                        if (o instanceof ApiModel) {
                            if (((ApiModel) o).code == ErrorCode.NorPermission.getCode()) {
                                doLogout(getUser());
                            }
                        }
                    }

                    @Override
                    public void onFailure(HttpException e, Response<?> response) {
                        response.printInfo();
                    }
                });
    }

    @Override
    protected Thread.UncaughtExceptionHandler createUncaughtExceptionHandler() {
        return new UncaughtHandler();
    }

    @Override
    protected DataBaseConfig createDatabaseConfig() {
        DataBaseConfig config = new DataBaseConfig(context);
        config.dbVersion = 1;
        return config;
    }

    public void loadImageForView(String uri, ImageView imageView) {
        ImageLoader.getInstance().displayImage(uri, imageView, getDefaultDisplayImageOptions());
    }

    public void loadRoundedImageForView(String uri, ImageView imageView) {
        ImageLoader.getInstance().displayImage(uri, imageView, getRoundedDisplayImageOptions());
    }

    public void loadImageForAvator(String uri, ImageView imageView) {
        ImageLoader.getInstance().displayImage(uri, imageView, new DisplayImageOptions.Builder()
                .bitmapConfig(Bitmap.Config.RGB_565)
                .cacheOnDisk(true)
                .displayer(new RoundedBitmapDisplayer(1000))
                .showImageForEmptyUri(R.drawable.icon_mine_head)
                .showImageOnFail(R.drawable.icon_mine_head)
                .showImageOnLoading(R.drawable.icon_mine_head)
                .cacheOnDisk(true).build());
    }

    /**
     * 从drawable中异步加载本地图片
     *
     * @param imageId
     * @param imageView
     */
    public void loadImageForDrawable(int imageId, ImageView imageView) {
        ImageLoader.getInstance().displayImage("drawable://" + imageId,
                imageView,getRoundedDisplayImageOptions());
    }

    public DisplayImageOptions getDefaultDisplayImageOptions() {
        return new DisplayImageOptions.Builder()
                .bitmapConfig(Bitmap.Config.RGB_565)
                .cacheOnDisk(true).build();
    }

    public DisplayImageOptions getRoundedDisplayImageOptions() {
        return new DisplayImageOptions.Builder()
                .bitmapConfig(Bitmap.Config.RGB_565)
                .cacheOnDisk(true)
                .displayer(new RoundedBitmapDisplayer(1000)).build();
    }

    private void initImageLoader() {
        DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder()
                .cacheOnDisk(true)
                .bitmapConfig(Bitmap.Config.RGB_565)
                .build();
        //File cacheDir = StorageUtils.getCacheDirectory(context);
        ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(context)
                //.memoryCacheExtraOptions(480, 800) // default = device screen dimensions
                //.diskCacheExtraOptions(480, 800, null)
                //.taskExecutor(new SmartExecutor())
                //.taskExecutorForCachedImages(new SmartExecutor(1, 100))
                //.threadPoolSize(3) // default
                //.threadPriority(Thread.NORM_PRIORITY - 2) // default
                //.tasksProcessingOrder(QueueProcessingType.FIFO) // default
                //.denyCacheImageMultipleSizesInMemory()
                //.memoryCache(new LruMemoryCache(2 * 1024 * 1024))
                //.memoryCacheSize(2 * 1024 * 1024)
                //.memoryCacheSizePercentage(13) // default
                //.diskCache(new UnlimitedDiscCache(cacheDir)) // default
                //.diskCacheSize(50 * 1024 * 1024)
                //.diskCacheFileCount(100)
                //.diskCacheFileNameGenerator(new HashCodeFileNameGenerator()) // default
                //.imageDownloader(new BaseImageDownloader(context)) // default
                //.imageDecoder(new BaseImageDecoder()) // default
                //.defaultDisplayImageOptions(DisplayImageOptions.createSimple()) // default
                //.writeDebugLogs()
                .defaultDisplayImageOptions(defaultOptions)
                .build();
        ImageLoader.getInstance().init(config);
    }

    public AppSdk setUser(User user) {
        if (user != null) {
            Log.i(TAG, "keep user: " + user);
            this.user = user;
            dataKeeper.put(AppConst.KEY_USER, user);
        }
        return this;
    }

    public User getUser() {
        return user;
    }







    /**
     * 登陆成功一定会调用这里
     *
     * @param user 当前登录用户
     */
    public void doLogin(User user) {
        Log.i("GetuiSdkDemo", "注册： 电话 个推  --------------------> " );
    }

    /**
     * 登出的时候一定会调用这里
     *
     * @param user 当前登录用户
     */
    public void doLogout(User user) {
        Log.i("GetuiSdkDemo", "解注： 电话 个推 -------------------->" );
        //        finishAllActivity();
        goToLoginActivity();
        setUser(new User());
    }

    public void goToLoginActivity() {
        String uri = AppConst.URI_LOGIN;
        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }


    public void doLoginAsync(LoginParam param, HttpListener<LoginModel> listener) {
        executeAsync(param.setHttpListener(
                new HttpListener<LoginModel>(false) {
                    @Override
                    public void onSuccess(LoginModel model, Response<LoginModel> response) {
                        if (model.hasResult()) {
                            setUser(model.result);
                            doLogin(getUser());
                        } else {
                            setUser(null);
                        }
                    }
                }.setLinkedListener(listener)));
    }


    public <T> JsonRequest<T> executeAsync(HttpRichParamModel<T> model) {
        return liteHttp.executeAsync(model);
    }

    public <T> void executeAsync(AbstractRequest<T> request) {
        liteHttp.executeAsync(request);
    }



}
